# coding=utf-8


import json
from datetime import datetime

from pony.orm import db_session, select
from tornado import web

from db.model import AuthToken


class BaseTornadoHandler(web.RequestHandler):
    """
    tornado base handler
    """

    def __init__(self, application, request, **kwargs):
        super(BaseTornadoHandler, self).__init__(application, request, **kwargs)

    def data_received(self, chunk):
        pass

    def try_get_json(self):
        try:
            body_str = self.request.body.decode('utf8')
            data = json.loads(body_str)
            return data
        except ValueError:
            return None

    @db_session
    def get_current_user(self):
        """
        check token is valid or not, if valid, return user
        """
        now = datetime.now()
        token = self.request.headers.get("Auth-Token", "")
        if not token:
            return None
        user = select(a.user for a in AuthToken if a.token == token and a.expire_time > now).first()
        return user
